from Products.Five.browser.pagetemplatefile import ViewPageTemplateFile
from plone.app.layout.viewlets.common import ViewletBase
from Acquisition import aq_inner
from zope.component import getMultiAdapter
from Products.CMFCore.utils import getToolByName
from Products.CMFPlone.utils import base_hasattr


class SiteLogoViewlet(ViewletBase):
    render = ViewPageTemplateFile('sitelogo.pt')

    def update(self):
        self.site = None
        context = aq_inner(self.context)
        site = None
        try:
            site = context.getSite()
        except:
            site = None
        if site != None:
            self.site = site
            self.logoUrl = 'logo_mini'
        else:
            portal_state = getMultiAdapter((context, self.request),name=u'plone_portal_state')
            self.site =  portal_state.portal()

            self.logoUrl = 'logo.png'

class SiteTopViewlet(ViewletBase):
    render = ViewPageTemplateFile('sitetop.pt')

    def update(self):
        self.chapters = None
        context = aq_inner(self.context)
        site = None
        try:
            site = context.getSite()
        except:
            site = None
        if site != None:
            self.chapters = site.getRelatedItems()

class GlobalSectionsViewlet(ViewletBase):
    index = ViewPageTemplateFile('sections.pt')

    def update(self):
        context = aq_inner(self.context)
        comixSite = None
        try:
            comixSite = context.getSite()
        except:
            comixSite = None
            
        if  comixSite != None:
            results = []
            for tab in comixSite.tabs:
                url = '%s/' % context.getSite().absolute_url()
                url = url + tab
                if tab =='':
                    tab = 'Home'
                data = {
                        'name'      : tab,
                        'id'         : tab,
                        'url'        :  url,
                        'description': ''
                        }
                results.append(data)
            self.portal_tabs = results
        else:
            portal_tabs_view = getMultiAdapter((context, self.request),
                                           name='portal_tabs_view')
            self.portal_tabs = portal_tabs_view.topLevelTabs()
        
        self.selected_tabs = self.selectedTabs(portal_tabs=self.portal_tabs)
        self.selected_portal_tab = self.selected_tabs['portal']

    def selectedTabs(self, default_tab='index_html', portal_tabs=()):
        plone_url = getToolByName(self.context, 'portal_url')()
        plone_url_len = len(plone_url)
        request = self.request
        valid_actions = []

        url = request['URL']
        path = url[plone_url_len:]

        for action in portal_tabs:
            if not action['url'].startswith(plone_url):
                # In this case the action url is an external link. Then, we
                # avoid issues (bad portal_tab selection) continuing with next
                # action.
                continue
            action_path = action['url'][plone_url_len:]
            if not action_path.startswith('/'):
                action_path = '/' + action_path
            if path.startswith(action_path + '/'):
                # Make a list of the action ids, along with the path length
                # for choosing the longest (most relevant) path.
                valid_actions.append((len(action_path), action['id']))

        # Sort by path length, the longest matching path wins
        valid_actions.sort()
        if valid_actions:
            return {'portal' : valid_actions[-1][1]}

        return {'portal' : default_tab}